package concurrent;

import java.util.concurrent.atomic.AtomicStampedReference;

/**
 * User: Administrator
 * Date: 2021/1/29
 * Time: 9:44
 * Description:
 * 实现一个简单的cas并发链表
 */
public class LockFreeList<E> {

    //AtomicStampedReference可以解决cas的ABA问题
    private AtomicStampedReference<Node<E>> headRef = null;

    public LockFreeList() {
        this.headRef = new AtomicStampedReference<>(null, 0);
    }

    private static class Node<E> {
        E element;
        Node<E> next;

        public Node(E element) {
            this.element = element;
        }
    }

    private void add(E element) {
        if (element == null) {
            throw new NullPointerException("element is null");
        }
        Node<E> preNode;
        int preStamp;
        Node<E> newNode;
        do {
            preNode = this.headRef.getReference();
            preStamp = this.headRef.getStamp();
            newNode = new Node<>(element);
            newNode.next = preNode;
        } while (!this.headRef.compareAndSet(preNode, newNode, preStamp, preStamp + 1));
    }
}
